#!/usr/bin/perl

use strict;

package main;

use Getopt::Long;
use XML::Simple;
use Lunmgr ':all';
use MSAUtils ':all';
use Data::Dumper;

my %_cmds = (
    egrep => '/bin/egrep',
);

my %_opts = (from => '/home/lunmgr/lunmgr.conf.xml');

GetOptions(\%_opts,
          "-msa=s@",
          "-from=s",
          "-to=s",
          "-help|h");

my @msas;
if ($_opts{msa}) {
    @msas = split(/,/, join(',', @{$_opts{msa}})) ;
}
else {
    chomp (@msas = `$_cmds{egrep} -o msa[0-9]+ /etc/hosts`);
}

my @wwns = GetWwnsForMsa(@msas);
my %dev_models = GetMsaModels(@msas);

my $lunmgr_conf = XMLin($_opts{from},
                   KeyAttr => [],
                   ForceArray => ['rack', 'port', 'disk_enclosure', 'lun']
                 );

my @devices;
foreach my $rack (@{$lunmgr_conf->{rack}}) {
    foreach my $port (@{$rack->{port}}) {
        next if ($port->{number} > 0);

        foreach my $enc (@{$port->{disk_enclosure}}) {
            next unless (grep(/$enc->{wwpn}/, @wwns));

            foreach my $lun (@{$enc->{lun}}) {
                next if ($lun->{id} >= 60);
                push @devices, Lunmgr::Device->new(
                                 uuid => $lun->{device},
                                 model => $dev_models{$enc->{wwpn}},
                                 wwn => $enc->{wwpn}, 
                                 lun => $lun->{id},
                                 mount_pt => $lun->{mount_pt}, 
                                 name => $lun->{name}
                    );
            }
        }
    }
}

my $fhbak;
if ($_opts{to}) {
    $fhbak = select;
    open my $fh, ">", "$_opts{to}" 
         or die "Could not write to file $_opts{to}\n";
    select $fh;
}

WriteTable(@devices);

select $fhbak if ($_opts{to});

